﻿namespace MqttClient.Code
{
    public class SampleBackgroundService : BackgroundService
    {
        private readonly ILogger<SampleBackgroundService> logger;
        public SampleBackgroundService(ILogger<SampleBackgroundService> logger)
        {
            this.logger = logger;
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("后台服务停止……");
            await Task.CompletedTask;
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("后台服务启动……");
            await Task.Factory.StartNew(async () => {
                while (!cancellationToken.IsCancellationRequested)
                {
                    logger.LogInformation($"后台服务执行中 - {DateTime.Now}");
                    try
                    {
                        await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
                    }
                    catch (OperationCanceledException) { }
                }
            }, cancellationToken);
        }
    }
}
